package ar.com.angrymachine.hunter.ui;

import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.Iterator;

import ar.com.angrymachine.hunter.Activity;
import ar.com.angrymachine.hunter.ActivitySet;
import ar.com.angrymachine.hunter.Game;
import ar.com.angrymachine.hunter.GraphicStyles;
import ar.com.angrymachine.gameui.ScrollingContainerWidget;
import ar.com.angrymachine.gameui.Widget;

public abstract class ActivityWidget extends ScrollingContainerWidget
{
    public ActivityWidget(Widget parent, Rectangle area)
    {
        super(parent, area);
    }
    
    protected abstract ActivitySet getActivitySet();
    
    public void paint(Graphics g)
    {
    	super.paint(g);
        Game game = Game.current;
        if (game != null)
        {
        	// update the bar size
        	int paintableHeight = getActivitySet().activities.size()*GraphicStyles.ACTIVITY_HEIGHT;
        	setAreaHeight(paintableHeight);
        	g.translate(0, -getCurrentOffset());
            // paint activities
            Rectangle activityArea = new Rectangle(0, 0,getWidth(),GraphicStyles.ACTIVITY_HEIGHT);
            for (Iterator iter = getActivitySet().activities.iterator(); iter.hasNext();)
            {
                Activity activity = (Activity) iter.next();
                if(activity.visible)
                {
	                activity.paint(g, activityArea);
	                if(activity == Game.current.getRunningActivity())
	                {
	                	g.setColor(GraphicStyles.selectedActivityColor());
	                	g.drawRect(activityArea.x, activityArea.y, activityArea.width-1, activityArea.height-1);
	                }
	                activityArea.y += GraphicStyles.ACTIVITY_HEIGHT;
                }
            }
            g.translate(0, getCurrentOffset());
        }
    }
    
    public void mouseDown(Point p)
    {
    	super.mouseDown(p);
        Game.current.resetActivity();
        // have in mind the offset
        p.y += getCurrentOffset();
        // determine if an activity is underneath
        int top = 0;
        for (Iterator iter = getActivitySet().activities.iterator(); iter.hasNext();)
        {
            Activity activity = (Activity) iter.next();
            if(activity.visible)
            {
	            if(p.y >= top && p.y < top + GraphicStyles.ACTIVITY_HEIGHT)
	            {
	                Game.current.setRunningActivity(activity);
	                break;
	            }
	            top += GraphicStyles.ACTIVITY_HEIGHT;
            }
        }
    }
    
    public void mouseUp(Point p)
    {
    	super.mouseUp(p);
        Game.current.resetActivity();
    }    
}
